const { app, BrowserWindow, dialog, ipcMain, shell } = require('electron');
const path = require('path');
const JSServer = require('./js_server');

let mainWindow;
let splashWindow;
let jsServer = null;
let serverUrl = null;

function createSplashWindow() {
  // 创建启动画面窗口
  splashWindow = new BrowserWindow({
    width: 400,
    height: 300,
    frame: false,
    alwaysOnTop: true,
    transparent: true,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true
    },
    icon: path.join(__dirname, process.platform === 'darwin' ? 'icon.icns' : 'icon.ico'),
    show: true
  });

  // 创建启动画面HTML内容
  const splashHTML = `
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {
                margin: 0;
                padding: 0;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                height: 100vh;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                color: white;
                border-radius: 10px;
            }
            .logo {
                width: 80px;
                height: 80px;
                background: white;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24px;
                font-weight: bold;
                color: #667eea;
                margin-bottom: 20px;
            }
            .title {
                font-size: 18px;
                font-weight: 600;
                margin-bottom: 10px;
            }
            .subtitle {
                font-size: 12px;
                opacity: 0.8;
                margin-bottom: 30px;
            }
            .loading {
                display: flex;
                align-items: center;
                gap: 10px;
            }
            .spinner {
                width: 20px;
                height: 20px;
                border: 2px solid rgba(255,255,255,0.3);
                border-top: 2px solid white;
                border-radius: 50%;
                animation: spin 1s linear infinite;
            }
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
            .status {
                font-size: 11px;
                opacity: 0.7;
                margin-top: 10px;
            }
        </style>
    </head>
    <body>
        <div class="logo">E2D</div>
        <div class="title">Excel2DbForAndroid</div>
        <div class="subtitle">Excel转SQLite数据库工具 (JavaScript版)</div>
        <div class="loading">
            <div class="spinner"></div>
            <span>正在启动应用...</span>
        </div>
        <div class="status">使用纯JavaScript技术，启动更快！</div>
    </body>
    </html>
  `;

  splashWindow.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(splashHTML));
}

function createWindow() {
  // 创建浏览器窗口
  mainWindow = new BrowserWindow({
    width: 500,
    height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    },
    icon: path.join(__dirname, process.platform === 'darwin' ? 'icon.icns' : 'icon.ico'),
    title: 'Excel2DbForAndroid (JavaScript版)',
    show: false // 先不显示，等服务器准备好
  });

  // 当窗口准备好显示时才显示
  mainWindow.once('ready-to-show', () => {
    // 关闭启动画面
    if (splashWindow) {
      splashWindow.close();
      splashWindow = null;
    }
    mainWindow.show();
    mainWindow.focus();
  });

  if (serverUrl) {
    // 加载服务器应用
    mainWindow.loadURL(serverUrl);
  } else {
    // 显示错误页面
    mainWindow.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(`
      <html>
        <body style="font-family: Arial; text-align: center; padding: 50px;">
          <h1>服务器启动失败</h1>
          <p>无法启动内置服务器，请重试。</p>
        </body>
      </html>
    `));
  }

  // 监听窗口关闭
  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

// 启动JavaScript服务器
async function startJSServer() {
  try {
    // 获取随机端口
    const port = Math.floor(Math.random() * 10000) + 10000;
    jsServer = new JSServer(port);
    
    const result = await jsServer.start();
    serverUrl = result.url;
    
    return result;
    
  } catch (error) {
    console.error('JavaScript服务器启动失败:', error);
    throw error;
  }
}

// 应用准备就绪
app.whenReady().then(async () => {
  console.log('Electron应用准备就绪');
  
  try {
    // 先显示启动画面
    createSplashWindow();
    
    // 启动JavaScript服务器（这个过程很快）
    await startJSServer();
    
    // 创建主窗口
    createWindow();
    
  } catch (error) {
    console.error('应用初始化失败:', error);
    
    // 关闭启动画面
    if (splashWindow) {
      splashWindow.close();
      splashWindow = null;
    }
    
    dialog.showErrorBox('应用启动失败', `初始化过程中出错: ${error.message}`);
    app.exit(1);
  }
});

// 所有窗口关闭时退出应用
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 应用激活时创建窗口
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// 应用退出前清理
app.on('before-quit', () => {
  console.log('应用即将退出，清理资源...');
  
  // 关闭JavaScript服务器
  if (jsServer && jsServer.server) {
    jsServer.server.close();
    console.log('JavaScript服务器已关闭');
  }
});

// IPC处理：打开外部链接
ipcMain.handle('open-external-link', async (event, url) => {
  try {
    await shell.openExternal(url);
    return { success: true };
  } catch (error) {
    console.error('打开外部链接失败:', error);
    return { success: false, error: error.message };
  }
});